from flask import Flask, request, session, url_for, current_app, g, redirect
from datetime import timedelta

from util import print_config

app = Flask(__name__)
app1 = Flask(__name__)
# 设置 secret key 的值
# app.secret_key = "Your secret key&^52@!"
app.config["SECRET_KEY"] = "Your secret key&^52@!"
app1.config["SECRET_KEY"] = "232434"
app.config["SESSION_COOKIE_NAME"] = "my_session"  # 修改 session cookie 名称

# Configure session to persist after browser closes
# app.permanent_session_lifetime = timedelta(hours=31)
with app.app_context():
    print(current_app.secret_key)


# 判断用了chrome还是edge浏览器访问页面
@app.route("/agent")
def index():
    user_agent = request.user_agent.string.lower()
    print(f"User-Agent: {user_agent}")
    if "edg" in user_agent:
        user_agent = "Edge"
    elif "chrome" in user_agent:
        user_agent = "Chrome"
    return f"User-Agent: {user_agent}"


# 获取url中的参数
@app.route("/args")
def args():
    user_name = request.args.get("name", "guest")
    method = request.method
    return f"args: {user_name} method: {method}"


@app.route("/home")
def home():
    # 如果cookie被禁用，session也无法使用
    # 用url参数判断是否登录
    # username = request.args.get("username", "")
    # print(username)
    # 用session判断是否登录
    # if "username" in session:
    #     username = session["username"]
    # return f" hello,{g.user}, this is home page."
    # return f" hello,{session['username']}, this is home page."
    #
    # 用cookie判断是否登录
    username = request.cookies.get("username", "")
    return f" hello,{username}, this is home page."


# @app.before_request
def check_login():
    if "username" in session:
        g.user = session["username"]
    elif request.endpoint != "login":
        return "未登录", 401
        # 如果没有登录，重新定向
        # return redirect(url_for("login"))


@app.route("/login", methods=["GET", "POST"])
def login():
    # 用session判断是否登录
    # if "username" in session:
    #     username = session["username"]
    #     return f"用户 {} 已登录!"
    # 用g对象来判断是否登录
    if hasattr(g, "user"):
        return f"用户 {g.user} 已登录!"

    if request.method == "POST":
        session["username"] = request.form["username"]  # 设置 session 值
        session.permanent = True  # 设置 session 永久有效 (31天)
        g.user = session["username"]
        return "登录成功! 现在你可以关闭浏览器，再重新打开访问 /home 页面，session应该还在。"
    #
    # rewrite use cookie to login
    # if request.method == "POST":
    #     resp = app.make_response(
    #         "登录成功! 现在你可以关闭浏览器，再重新打开访问 /home 页面，session应该还在。"
    #     )
    #     resp.set_cookie(
    #         "username", request.form["username"], max_age=60 * 60 * 24 * 30
    #     )  # Cookie 有效期30天
    #     return resp

    return """
        <form method="get" action="/submit">
        <p><input type=text name=username1 placeholder="输入用户名">
        <p><input type=submit value='登录'>
        </form>
        """


@app.route("/submit")
def submit():
    username = request.args.get("username", "guest")
    return app.make_response(f"提交成功! 用户名: {username}")


@app.route("/set_cookie")
def set_cookie():
    response = app.make_response("Cookie has been set!")
    response.headers["user-agent"] = "Internet Explorer"
    response.set_cookie(
        "my_cookie", "mypassword", max_age=60 * 60 * 24 * 30
    )  # Cookie 有效期30天
    return response


@app.route("/get_cookie")
def get_cookie():
    session_value = request.cookies.get("my_session", "Not Set")
    cookie_value = request.cookies.get("my_cookie", "Not Set")
    return f"Cookie Value: {cookie_value}"


@app.route("/hello/<string:busername>")
def hello(busername):
    return f"{url_for('hello', busername=busername, page=3, _external=True)}"


@app.route("/hello")
def hello_no_arg():
    page = request.args.get("page", 1)
    return f"hello, page {page}"


@app.route("/logout")
def logout():
    session.clear()  # 清除所有session数据
    return "已退出登录!"


# current_app 代表当前激活的 Flask 应用实例
@app.route("/show_config")
@app1.route("/show_config")
def show_config():
    # print_config()
    config = current_app.config["SECRET_KEY"]
    return config
    # return "config printed to console"


# g对象用于在请求期间存储和共享数据
@app.route("/add/<int:a>/<int:b>")
def add_route(a, b):
    result = a + b  # This sets g.result
    g.result = result
    return f"计算结果: {a} + {b} = {result}"


# g只在同一个request中有效，所以这里g.result是没有值的
@app.route("/get_result")
def get_result():
    return f"计算结果是: {g.result}"


# 书p033例子
@app.route("/")
def get_user():
    g.user_id = "001"  # 将用户id保存到g对象中
    g.user_name = "flask"  # 将用户名称保存到g对象中
    result = db_query()
    return f"{result}"


def db_query():
    user_id = g.user_id  # 使用g对象获取用户id
    user_name = g.user_name  # 使用g对象获取用户名称
    with open("log.txt", "a") as f:
        f.write(f"user_id: {user_id}, user_name: {user_name}\n")


@app.route("/current_app")
def current_app_route():
    return f"Current App Name: {current_app.secret_key}"


if __name__ == "__main__":
    app.run(debug=True, port=5013)
    # app1.run(debug=True, port=5014)
